package com.chainyoung.component_tmtrade.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chainyoung.common.appcommon.entity.RecieveAccount;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.CommonStringConstants;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.FixedCursorEditText;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmtrade.R;
import com.chainyoung.component_tmtrade.R2;
import com.chainyoung.component_tmtrade.bean.FiatTradeListItem;
import com.chainyoung.component_tmtrade.bean.TradeResult;
import com.chainyoung.component_tmtrade.constant.StringConstant;
import com.chainyoung.component_tmtrade.di.component.DaggerTradeFiatCurrencyActivityComponent;
import com.chainyoung.component_tmtrade.di.module.TradeFiatCurrencyActivityModule;
import com.chainyoung.component_tmtrade.ui.mvp.contract.TradeFiatCurrencySubmitOrderContract;
import com.chainyoung.component_tmtrade.ui.mvp.presenter.TradeFiatCurrencySubmitOrderPresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.chainyoung.common.constant.CommonStringConstants.NUM;
import static com.chainyoung.common.constant.CommonStringConstants.RMB;
import static com.chainyoung.component_tmtrade.constant.StringConstant.FIAT_COIN_NAME;

public class SubmitFiatCurrencyTradeOrderActivity extends BaseActivity<TradeFiatCurrencySubmitOrderPresenter> implements TradeFiatCurrencySubmitOrderContract.View {


    @BindView(R2.id.txt_evaluate)
    TextView txtEvaluate;
    @BindView(R2.id.et_evaluate)
    TextView etEvaluate;
    @BindView(R2.id.txt_num)
    TextView txtNum;
    @BindView(R2.id.et_trade_num)
    FixedCursorEditText etTradeNum;
    @BindView(R2.id.txt_total_money)
    TextView txtTotalMoney;
    @BindView(R2.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R2.id.txt_pay_method)
    TextView txtPayMethod;
    @BindView(R2.id.tv_set_pay_method)
    TextView tvSetPayMethod;
    @BindView(R2.id.iv_method1)
    ImageView ivMethod1;
    @BindView(R2.id.iv_method2)
    ImageView ivMethod2;
    @BindView(R2.id.iv_method3)
    ImageView ivMethod3;
    @BindView(R2.id.rl_set_pay_method)
    RelativeLayout rlSetPayMethod;
    @BindView(R2.id.txt_bit)
    TextView txtBit;

    private FiatTradeListItem item;
    private int type;//买 卖订单类型
    private boolean isHasOpen = false;//卖出订单时是否开启收款账户
    private String price;
    private String num;
    private String limitNum;
    private List<String> bankIds = new ArrayList<>();

    private static final int TYPE_BUY = 1;
    private static final int TYPE_SELL = 2;
    private String coinName;//法币名称


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTradeFiatCurrencyActivityComponent.builder()
                .appComponent(appComponent)
                .tradeFiatCurrencyActivityModule(new TradeFiatCurrencyActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        item = getIntent().getParcelableExtra(StringConstant.FIAT_CURRENCY_TRADE_ITEM);
        type = getIntent().getIntExtra(CommonStringConstants.TYPE, TYPE_BUY);//1:买 2：卖
        limitNum = getIntent().getStringExtra(NUM);
        coinName=getIntent().getStringExtra(FIAT_COIN_NAME);


        setCurrentTitle(type == TYPE_BUY ? getString(R.string.tmtrade_buy_order) : getString(R.string.tmtrade_sell_order));

        txtEvaluate.setText(type == TYPE_BUY ? R.string.tmtrade_evaluate_buy : R.string.tmtrade_evaluate_sell);
        txtNum.setText(type == TYPE_BUY ? R.string.tmtrade_buy_in_num : R.string.tmtrade_sell_out_num);
        etTradeNum.setHint(String.format(mContext.getString(R.string.tmtrade_limit_num), limitNum));
        txtBit.setText(coinName.toUpperCase());

        rlSetPayMethod.setVisibility(type == TYPE_BUY ? View.GONE : View.VISIBLE);

        price = item.getPrice_cny();
        etEvaluate.setText(String.format("%s", new BigDecimal(price).setScale(2, BigDecimal.ROUND_DOWN)));

        etTradeNum.addTextChangedListener(new TextWatcher() {
            boolean deleteLastChar;// 是否需要删除末尾

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.toString().contains(".")) {
                    // 如果点后面有超过6位数值,则删掉最后一位
                    int length = s.length() - s.toString().lastIndexOf(".");
                    // 说明后面有6位数值
                    deleteLastChar = length >= 8;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (deleteLastChar) {
                    // 设置新的截取的字符串
                    etTradeNum.setText(s.toString().substring(0, s.toString().length() - 1));
                    // 光标强制到末尾
                    etTradeNum.setSelection(etTradeNum.getText().length());
                    KProgressHUD.create(mContext)
                            .setCustomView(mContext, R.drawable.tips_correct)
                            .setLabel(getString(R.string.tmtrade_only_six))
                            .show().setDuration(1500);
                }

                // 以小数点开头，前面自动加上 "0"
                if (s.toString().startsWith(".")) {
                    etTradeNum.setText("0" + s);
                    etTradeNum.setSelection(etTradeNum.getText().length());
                }
                if (s.toString().startsWith("0") && (s.toString().length() > 1) && !s.toString().startsWith("0.")) {
                    etTradeNum.setText(s.toString().substring(1));
                    etTradeNum.setSelection(etTradeNum.getText().length());
                }

                if (!TextUtils.isEmpty(currString) && s.length() > currString.length() && isAboveMax) {
                    etTradeNum.setText(currString);
                    etTradeNum.setSelection(currString.length());
                }

                if (!TextUtils.isEmpty(etTradeNum.getText().toString().trim())) {
                    if (Double.valueOf(etTradeNum.getText().toString().trim()) > Double.valueOf(limitNum)) {
                        etTradeNum.setText(limitNum);
                        etTradeNum.setSelection(limitNum.length());
                        return;
                    }
                }
                //mHandler.removeCallbacks(mRunnable);
                //1.5秒没有输入认为输入完毕
                // mHandler.postDelayed(mRunnable, 1500);
                reCountTotalMoney();
            }
        });


    }


    private static final int EDIT_OK = 0x001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (EDIT_OK == msg.what) {
                reCountTotalMoney();
            }

        }
    };

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {

            mHandler.sendEmptyMessage(EDIT_OK);
        }
    };

    private boolean isBelowMin = false;
    private boolean isAboveMax = false;
    private String currString;

    private void reCountTotalMoney() {
        num = etTradeNum.getText().toString().trim();
        if (TextUtils.isEmpty(price) || TextUtils.isEmpty(num)) {
            tvTotalMoney.setText("0");
            return;
        }
        tvTotalMoney.setText(RMB + new BigDecimal(price).multiply(new BigDecimal(num)).setScale(2, BigDecimal.ROUND_DOWN).toString());
        if (new BigDecimal(price).multiply(new BigDecimal(num)).compareTo(new BigDecimal(item.getTrade_min())) < 0) {
            isBelowMin = true;
            isAboveMax = false;
            // showMinDialog();
        } else if (new BigDecimal(price).multiply(new BigDecimal(num)).compareTo(new BigDecimal(item.getTrade_max())) > 0) {
            isAboveMax = true;
            isBelowMin = false;
            showMaxDialog();
        } else {
            isBelowMin = false;
            isAboveMax = false;
        }
        currString = etTradeNum.getText().toString();
    }

    private void showMinDialog() {
        KProgressHUD.create(this)
                .setCustomView(mContext, R.drawable.tips_error)
                .setLabel(getString(R.string.tmtrade_cannot_below_min))
                .show().setDuration(1500);
    }

    private void showMaxDialog() {
        KProgressHUD.create(this)
                .setCustomView(mContext, R.drawable.tips_error)
                .setLabel(getString(R.string.tmtrade_cannot_above_max))
                .show().setDuration(1500);
    }

    private void showNoDataDialog() {
        KProgressHUD.create(this)
                .setCustomView(mContext, R.drawable.tips_error)
                .setLabel(getString(R.string.tmtrade_pls_input_trade_num))
                .show().setDuration(1500);
    }


    private void showOpenAccountDialog() {
        KProgressHUD.create(this)
                .setCustomView(mContext, R.drawable.tips_error)
                .setLabel(getString(R.string.tmtrade_pls_open_recieve_account))
                .show().setDuration(1500);
    }

    @Override
    protected void initData() {
        if (type == TYPE_SELL) {
            getAccounts();
        }

    }

    /**
     * 获取收款账户
     */
    private void getAccounts() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        mPresenter.getRecieveAccount(map);
    }


    @OnClick({R2.id.rl_set_pay_method, R2.id.tv_submit})
    void onClick(View v) {
        if (v.getId() == R.id.rl_set_pay_method) {
            RouterUtils.getInstance()
                    .build(RouterConstants.PATH_RECIEVE_ACCOUNT)
                    .navigation(this);
        } else if (v.getId() == R.id.tv_submit) {
            if (StringUtil.viewGetTextIsEmpty(etTradeNum)) {
                showNoDataDialog();
                return;
            }
            if (isBelowMin) {
                showMinDialog();
                return;
            } else if (isAboveMax) {
                showMaxDialog();
                return;
            }
            if (type == TYPE_SELL && !isHasOpen) {
                showOpenAccountDialog();
                return;
            }

            mPresenter.checkSubmit(type, item.getId(), price, num, bankIds, getString(R.string.tmtrade_submit_order_in_progress),coinName);
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.tmtrade_activity_submit_order;
    }


    @Override
    public void onSubmitOrderSuccess(TradeResult result) {
        ToastUtil.showToast(result.getMessage());
        Intent intent = new Intent(mContext, TradeFiatCurrencyOrderDetailActivity.class);
        intent.putExtra(StringConstant.ID, result.getId());
        mContext.startActivity(intent);
        finish();
    }


    @Override
    public void onGetRecieveAccount(List<RecieveAccount> data) {
        int openNums = 0;
        if (!data.isEmpty()) {
            for (RecieveAccount account : data) {
                if (account.getOpen() == 1) {
                    bankIds.add(account.getId());
                    checkAccountOpen(account.getType());
                    openNums++;
                }
            }
            isHasOpen = openNums > 0;
        } else {
            tvSetPayMethod.setText(R.string.tmtrade_goto_set);
            isHasOpen = false;
        }
        tvSetPayMethod.setText(isHasOpen ? "" : getString(R.string.tmtrade_goto_set));
    }

    /**
     * 校验账户是否开启
     *
     * @param type
     */
    private void checkAccountOpen(int type) {
        tvSetPayMethod.setText("");
        switch (type) {
            case 1:
                ivMethod1.setImageResource(R.mipmap.ic_bank_card);
                break;
            case 2:
                ivMethod2.setImageResource(R.mipmap.ic_alipay);
                break;
            case 3:
                ivMethod3.setImageResource(R.mipmap.ic_weixin);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (type == TYPE_SELL) {
            ivMethod1.setImageResource(0);
            ivMethod2.setImageResource(0);
            ivMethod3.setImageResource(0);
            getAccounts();
        }
    }
}
